import 'package:custom_pop_up_menu/custom_pop_up_menu.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat_ui/models/chat_session_model.dart';
import 'package:flutter_chat_ui/pages/chat_room_controller.dart';
import 'package:flutter_chat_ui/utils/dialog_utils.dart';
import 'package:flutter_chat_ui/utils/getx_update_keys.dart';
import 'package:flutter_chat_ui/utils/x_load_svg.dart';
import 'package:flutter_chat_ui/utils/utils.dart';
import 'package:flutter_chat_ui/views/chat_app_bar_title_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

///
/// 聊天室侧边栏会话列表页面
///
class ChatRoomDrawerPage extends StatelessWidget {
  /// 点击新对话
  final VoidCallback? onNewChatClick;

  /// 点击某个会话
  final ValueChanged<ChatSessionData?>? onChatSessionClick;

  const ChatRoomDrawerPage({
    super.key,
    this.onNewChatClick,
    this.onChatSessionClick,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff3f3f3),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          /// 顶部标题
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8),
            margin: EdgeInsets.only(top: ScreenUtil().statusBarHeight + 20),
            child: Row(
              children: [
                /// 列表图标
                XSvgImage.load('icon_chat_session', width: 60, height: 60),

                /// 标题
                const Expanded(child: ChatAppBarTitleView())
              ],
            ),
          ),

          /// 新对话
          GestureDetector(
            onTap: onNewChatClick,
            child: Container(
              width: double.infinity,
              alignment: Alignment.centerLeft,
              margin: const EdgeInsets.only(top: 20, left: 12, right: 12),
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
              decoration: BoxDecoration(
                color: const Color(0xffE5EBF7),
                borderRadius: BorderRadius.circular(10),
                border: Border.all(
                  color: const Color(0xff155AEF),
                  width: 0.5,
                ),
              ),
              child: const Text(
                '+ 新对话',
                style: TextStyle(
                  fontSize: 18,
                  color: Color(0xff155AEF),
                  fontWeight: FontWeight.w700,
                ),
              ),
            ),
          ),

          /// 会话列表
          Expanded(
            child: GetBuilder<ChatRoomController>(
              id: GetxUpdateKeys.chatSessionListId,
              builder: (controller) {
                return ListView.separated(
                  itemCount: controller.chatSessionList.length,
                  padding: const EdgeInsets.only(top: 20),
                  shrinkWrap: true,
                  itemBuilder: (context, index) {
                    final session = controller.chatSessionList[index];

                    return ChatSessionItemView(
                      key: ValueKey(session.id),
                      session: session,
                      popMenu: _PopMenuView(
                        key: ValueKey(session.id),
                        menuController: controller.getChatSessionMenuController(session.id ?? ''),
                        onMenuTap: (value) {
                          switch (value) {
                            case ChatSessionMoreType.rename:
                              // 确认会话名的弹窗
                              DialogUtils.showEditSessionNameDialog(
                                context,
                                defaultName: session.name ?? '',
                                onRename: (value) => controller.renameSession(
                                  session.id ?? '',
                                  inputQuery: value,
                                ),
                              );
                              break;
                            case ChatSessionMoreType.delete:
                              DialogUtils.showDeleteSessionDialog(
                                context,
                                onDelete: () => controller.deleteSession(session, index: index),
                              );
                              break;
                          }
                        },
                      ),
                      onTap: onChatSessionClick,
                    );
                  },
                  separatorBuilder: (context, index) => Divider(
                    height: 0.5,
                    thickness: 0.0,
                    color: Colors.black.withValues(alpha: 0.25),
                    indent: 12,
                    endIndent: 12,
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

///
/// 会话列表Cell
///
final class ChatSessionItemView extends StatelessWidget {
  /// 外界传值
  final ChatSessionData? session;
  final Widget? popMenu;
  final ValueChanged<ChatSessionData?>? onTap;

  const ChatSessionItemView({
    super.key,
    this.session,
    this.popMenu,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => onTap?.call(session),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            /// 图标
            Container(
              margin: const EdgeInsets.only(top: 11),
              child: XSvgImage.load(
                'icon_chat_session_item',
                width: 20,
                height: 20,
              ),
            ),

            /// 文本
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  session?.name ?? ''.fixAutoLines(),
                  maxLines: 1,
                  style: const TextStyle(
                    fontSize: 16,
                    color: Colors.black,
                    fontWeight: FontWeight.normal,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
            ),

            /// ... 显示菜单
            popMenu ?? const SizedBox.shrink(),
          ],
        ),
      ),
    );
  }
}

///
/// 会话菜单视图
///
class _PopMenuView extends StatelessWidget {
  final CustomPopupMenuController menuController;
  final ValueChanged<ChatSessionMoreType>? onMenuTap;

  const _PopMenuView({
    super.key,
    required this.menuController,
    this.onMenuTap,
  });

  @override
  Widget build(BuildContext context) {
    return CustomPopupMenu(
      controller: menuController,
      pressType: PressType.singleClick,
      verticalMargin: -10,
      arrowColor: Colors.white,
      menuBuilder: () => _MenuBuilderView(
        onTap: (type) {
          menuController.hideMenu();
          onMenuTap?.call(type);
        },
      ),
      child: IconButton(
        onPressed: () => menuController.showMenu(),
        icon: Icon(
          Icons.more_horiz,
          color: Colors.black.withValues(alpha: 0.5),
        ),
        style: ButtonStyle(
          padding: WidgetStateProperty.all(const EdgeInsets.all(8.0)),
          minimumSize: WidgetStateProperty.all(Size.zero),
          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
        ),
      ),
    );
  }
}

///
/// builder菜单小部件
///
class _MenuBuilderView extends StatelessWidget {
  final ValueChanged<ChatSessionMoreType>? onTap;

  const _MenuBuilderView({
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(5),
      child: Container(
        color: Colors.white,
        child: IntrinsicWidth(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: _menuInfos
                .map((item) => Column(
                      children: [
                        /// 菜单item
                        GestureDetector(
                          behavior: HitTestBehavior.translucent,
                          onTap: () => onTap?.call(item.type),
                          child: Container(
                            height: 40,
                            padding: const EdgeInsets.only(left: 8, right: 12),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                /// 图标
                                XSvgImage.load(
                                  item.icon,
                                  width: 20,
                                  height: 20,
                                ),

                                /// 文本
                                Expanded(
                                  child: Container(
                                    margin: const EdgeInsets.only(left: 5),
                                    padding: const EdgeInsets.symmetric(vertical: 10),
                                    child: Text(
                                      item.title,
                                      style: TextStyle(
                                        color: item.textColor,
                                        fontSize: 14,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),

                        /// 添加下划线
                        Divider(
                          height: 0.5,
                          thickness: 0.5,
                          color: Colors.grey.withValues(alpha: 0.25),
                          indent: 8,
                          endIndent: 8,
                        ),
                      ],
                    ))
                .toList(),
          ),
        ),
      ),
    );
  }
}

///
/// 会话菜单信息模型
///
class _ChatSessionMenuInfo {
  final String icon;
  final String title;
  final Color textColor;
  final ChatSessionMoreType type;

  const _ChatSessionMenuInfo({
    required this.icon,
    required this.title,
    required this.type,
    this.textColor = Colors.black,
  });
}

const _menuInfos = [
  _ChatSessionMenuInfo(
    icon: 'icon_session_rename',
    title: '重新命名',
    type: ChatSessionMoreType.rename,
  ),
  _ChatSessionMenuInfo(
    icon: 'icon_session_delete',
    title: '删除',
    type: ChatSessionMoreType.delete,
    textColor: Colors.red,
  ),
];
